package com.wechat.common;

import com.alibaba.fastjson.JSONException;

import com.wechat.constant.JSApiList;
import com.wechat.pojo.WeChatToken;
import com.wechat.pojo.WeChatUserInfo;
import com.wechat.uitls.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class WeChatUtils {

    private String appSecret;
    private String appId;

    public WeChatUtils() {
    }

    public WeChatUtils(String appSecret, String appId) {
        this.appId = appId;
        this.appSecret = appSecret;
    }

    /**
     * 获取接口访问凭证
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public WeChatToken getPublicNumberAccessToken(String appid, String appsecret) {
        System.out.println("获取接口访问凭证");
        WeChatToken token = null;
        String requestUrl = JSApiList.ACCESS_TOKEN_URL.getUrl().replace("APPID", appid).replace("APPSECRET", appsecret);
        // 发起GET请求获取凭证
        JSONObject jsonObject = HttpRequest.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                token = new WeChatToken();
                token.setToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return token;
    }

    public  WeChatToken getJsapiTicket(String accessToken) {
        WeChatToken token = null;
        String requestUrl = JSApiList.JSAPI_TICKET.getUrl().replace("ACCESS_TOKEN", accessToken);
        // 发起GET请求获取凭证
        JSONObject jsonObject = HttpRequest.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                token = new WeChatToken();
                token.setToken(jsonObject.getString("ticket"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return token;
    }

    public String sha1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuilder hexString = new StringBuilder();
            // 字节数组转换为 十六进制 数
            for (byte b : messageDigest) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("微信签名时失败,请检查!", e);
        }
        return "";
    }



    // 获取前台传过来的Code，获取微信账号的OpenID
    public  WeChatUserInfo getWeCatAccountInformation(String code){
        // 请求微信服务器，请求成功后，用户会返回一个 WeChatUserInfo.class类型的Json数据包，Json转对象后，去除OpenID
        String url = JSApiList.GET_AUTHORIZATION_ACCESS_TOKEN_URL.getUrl().replace("APPID", appId);
        url = url.replace("SECRET", appSecret);
        url = url.replace("CODE", code);
        JSONObject jso = HttpRequest.httpsRequest(url, "GET", "");
        WeChatUserInfo WeChatUserInfo = (WeChatUserInfo) JSONObject.toBean(jso, WeChatUserInfo.class);
        return WeChatUserInfo;
    }

}
